package com.pfzy.ui.activity.voice;

import android.media.AudioRecord;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.Vibrator;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.RecyclerView;

import com.pfzy.ui.R;
import com.pfzy.ui.databinding.ActivityVoiceBinding;
import com.pfzy.ui.log.MyLog;
import com.pfzy.ui.utils.AudioCacheUtil;

import java.io.File;

import static com.pfzy.ui.utils.CommonUtil.getContext;

public class VoiceActivity extends AppCompatActivity implements View.OnClickListener {
    private ActivityVoiceBinding mBind;
    private MediaRecorder mMediaRecorder;
    private RecordAnimationView mRecordAnimationView;
    private int mBufferSize;
    private AudioRecord mAudioRecord;
    private boolean isRecording = false;
    //    RecordButton button;
    RecordAnimationView mRecord;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mBind = ActivityVoiceBinding.inflate(getLayoutInflater());
        setContentView(mBind.getRoot());
        initView();
    }

    private void initView() {
        TextView title = mBind.toolbar.findViewById(R.id.layout_toolbar_title);
        title.setText("录音");
        mBind.toolbar.findViewById(R.id.layout_toolbar_back).setOnClickListener(this);

        mBind.voiceStart.setOnClickListener(this);
        mBind.voiceEnd.setOnClickListener(this);
        wxVoiceButton = mBind.texture;

        ImRecordDialogManager.init(this);

        mBind.imVoiceBtn.setEnabled(false);
        mBind.imVoiceBtn.setRecordListener(new ImageViewVoiceButton.RecordListener() {
            @Override
            public void onStartRecording() {
//                mAdapter.stopPlayProxy();
                _logd("[===开始录音===]");
                ImRecordDialogManager.show();
                ImRecordDialogManager.updateShowStatus(ImRecordDialogManager.STATUS_NOMAL);
//                addPreViewRecord();
            }

            @Override
            public void onRecordTransformCancel() {
                _logd("[===松手取消===]");
                ImRecordDialogManager.updateShowStatus(ImRecordDialogManager.STATUS_UP_CANCEL);
            }

            @Override
            public void onRecordNormal() {
                _logd("[===正常录音录音===]");
                ImRecordDialogManager.updateShowStatus(ImRecordDialogManager.STATUS_NOMAL);
            }

            @Override
            public void onRecordCancel() {
                _logd("[===取消录音===]");
                cancelRecord();
            }

            @Override
            public void onRecordComplete(long interval, String filePath, int code) {
                mBind.imVoiceBtn.setSelected(false);
                File file = new File(filePath);
                _logd("[====录音结束===]" + interval + "[code] " + code);
                _logd("[====录音文件存在否===]" + file.exists() + " 文件大小:" + file.length());
                ImRecordDialogManager.dismiss();
                if (file.exists() && file.length() > 0) {
                    try {
                        // 默认Lru算法存储文件
                        AudioCacheUtil.getLruDiskUsage().touch(file);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                _logd("onEncodeComplete");
            }

            @Override
            public void onBadRecording(int code) {
                switch (code) {
                    case ImageViewVoiceButton.CODE_BAD_TIME:
                        ImRecordDialogManager.updateShowStatus(ImRecordDialogManager.STATUS_UP_SHORT);
                        break;
                    case ImageViewVoiceButton.CODE_RECORD_FAILED:
                        ImRecordDialogManager.updateShowStatus(ImRecordDialogManager.STATUS_RECORD_ERROR);
                        break;
                }
                mBind.imVoiceBtn.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        ImRecordDialogManager.dismiss();
                    }
                }, 1000L);
            }

            @Override
            public void onRecording(long interval) {
                _logd("[====录音时间：===]" + interval);

                int maxAmplitude = AudioRecorder.getInstance().getMaxAmplitude();
                int db = maxAmplitude / 35;
                db = Math.min(200, db);
                ImRecordDialogManager.updateRecordMaxAmplitude(db);
            }

            @Override
            public boolean havePermissionsDeny() {
                return true;
//                return ImPermissionWarp.wrapPermissionDeny(ConversationActivity.this);
            }

            @Override
            public void havingRecordingEvent() {
                _logd("司乘IM页面 当前有其他录音活动，所以不能发送语音");
//                ImToast.showToast(LocaleUtil.getLocalContext(null).getString(R.string.sdk_im_current_have_other_recording_so_not_send_voice));
            }
        });
    }

    @Override
    public void onClick(View v) {
        Log.d("录音", "按下 id" + v.getId());
        switch (v.getId()) {
            case R.id.layout_toolbar_back:
                finish();
                break;
            case R.id.voice_start:
                ImRecordDialogManager.show();
                ImRecordDialogManager.updateShowStatus(ImRecordDialogManager.STATUS_NOMAL);
//                voiceStart();
                break;
            case R.id.voice_end:
                Log.d("录音", "按下");
                ImRecordDialogManager.dismiss();
//                stopRecording();
                break;
            default:
                break;
        }
    }

    private void voiceStart() {
        this.path = new File(getCacheDir(), System.currentTimeMillis() + ".aac").getAbsolutePath();
        AudioRecorder.getInstance().start(path);
        startTime = System.currentTimeMillis();
        runningObtainDecibelThread = true;
        mThread = new ObtainDecibelThread();
        mThread.start();
    }


    private String path;
    /**
     * 最短录音时间
     **/
    private int MIN_INTERVAL_TIME = 1000;
    /**
     * 最长录音时间
     **/
    private int MAX_INTERVAL_TIME = 1000 * 60;

    private ObtainDecibelThread mThread;
    private boolean runningObtainDecibelThread = true;
    private long startTime;
    private volatile boolean firstNotice = true;
    private WXVoiceButton wxVoiceButton;

    /**
     * 用来定时获取录音的声音大小，以驱动动画
     * 获取录音时间，提醒用户
     * 到达最大时间以后自动停止
     */
    private class ObtainDecibelThread extends Thread {
        @Override
        public void run() {
            while (runningObtainDecibelThread) {
                if (!runningObtainDecibelThread) {
                    break;
                }

                // int x = recorder.getMaxAmplitude(); //振幅
                int maxAmplitude = AudioRecorder.getInstance().getMaxAmplitude();
                int db = maxAmplitude / 35;
                db = Math.min(200, db);

                long now = System.currentTimeMillis();
                long useTime = now - startTime;
                if (useTime > MAX_INTERVAL_TIME) {
                    stopRecording();
                    return;
                }
                //少于十秒则提醒
                long lessTime = (MAX_INTERVAL_TIME - useTime) / 1000;
                if (lessTime < 10) {
                    wxVoiceButton.setContent(lessTime + "秒后将结束录音");
                    if (firstNotice) {
                        firstNotice = false;//第一次需要震动
                        Vibrator vibrator = (Vibrator) getContext().getSystemService(getContext().VIBRATOR_SERVICE);
                        vibrator.vibrate(500);
                    }
                } else {
                    wxVoiceButton.addVoiceSize(db);
                }

                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }

    }

    private void stopRecording() {
        runningObtainDecibelThread = false;
        if (mThread != null) {
            mThread = null;
        }
        AudioRecorder.getInstance().stop();
//        if (mRecorder != null) {
//            try {
//                mRecorder.stop();//停止时没有prepare，就会报stop failed
//                mRecorder.reset();
//                mRecorder.release();
//                mRecorder = null;
//            } catch (RuntimeException pE) {
//                pE.printStackTrace();
//            } finally {
//            }
//        }
//        if (recordDialog != null) {
//            recordDialog.dismiss();
//            recordDialog = null;
//        }
        if (wxVoiceButton != null) {
            wxVoiceButton.quit();
            wxVoiceButton = null;
        }
    }

    @Override
    public void onDestroy() {
//        ImmersionBar.with(this).destroy();
//        finishCSBroadcast(this.context);
//        if (this.handler != null) {
//            this.handler.removeCallbacksAndMessages(null);
//            this.handler = null;
//        }
//        ImConstant.setIsChatUiLiving(false);
//        ImConstant.mChatOppositeId = "";
        ImRecordDialogManager.destroy();
//        this.mAdapter.releaseAudioPlayer();
//        ImToast.onDestyoy();
//        UiThread.clearCallBack();
//        UxImApi.removePushMessageObserver(this);
//        UxImApi.removeWebSocketStatusChangedListener(this.statusChangedListener);
//        hideTalkLoading();
//        InputUtils.saveStatus(this.context, this.im_img_voice.isSelected() ? 2L : 1L);
//        LocalBroadcastManager.getInstance(this).unregisterReceiver(this.mBroadcastReceiver);
//        this.im_edit_input.removeTextChangedListener(this.watcher);
        super.onDestroy();
//        dismissEndSessionDialog();
//        if (this.mSelectImageDialog != null && this.mSelectImageDialog.isShowing()) {
//            this.mSelectImageDialog.dismiss();
//            this.mSelectImageDialog = null;
//        }
    }

    public void cancelRecord() {
        ImRecordDialogManager.dismiss();
        mBind.imVoiceBtn.cancelRecord();
    }

    private void _logd(String msg) {
        MyLog.logd("即时通讯: $msg");
    }
}
